package testcontroller;

import java.util.Random;

public class WeixinService {
    private WeixinService() {}

    private static class SingletonHolder {
        private final static WeixinService instance = new WeixinService();
    }

    public static WeixinService getInstance() {
        return SingletonHolder.instance;
    }

    // token
    private static String ACCESS_TOKEN = "";

    // token过期时间
    private static int ACCESS_TOKEN_EXPIRE_TIME = 0;

    /**
     * 获取前判断有没有超时，超时则更新
     * 
     * @return
     */
    public String getAccessToken() {
        if (ACCESS_TOKEN_EXPIRE_TIME < now()) {
            updateAccessToken();
        }
        System.out.println("ACCESS_TOKEN_EXPIRE_TIME=" + ACCESS_TOKEN_EXPIRE_TIME);
//        System.out.println("ACCESS_TOKEN=" + ACCESS_TOKEN);
        return ACCESS_TOKEN;
    }

    /**
     * @return
     */
    private int now() {
        return (int)(System.currentTimeMillis() / 1000L);
    }

    /**
     * 
     */
    private void updateAccessToken() {
        System.out.println("WeixinService.updateAccessToken()");
        // 赋值10秒有效期
        ACCESS_TOKEN_EXPIRE_TIME = now() + 10;
        Random random = new Random();
        ACCESS_TOKEN = random.nextInt(100000) + "";
    }

}
